<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use App\Exceptions\BusinessException;
use App\Http\Response\ResponseEnum;
use App\Services\JwtService;
use App\Models\Admin;

class AdminAuth
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        $request->attributes->remove('admin_info');

        $authorization = $request->header('Authorization', '');

        if (!$authorization) {
            throw new BusinessException(ResponseEnum::CLIENT_HTTP_UNAUTHORIZED, 'token not exist');
        }

        $arr = explode(' ', $authorization);

        $token = $arr[1] ?? '';

        if (!$token) {
            throw new BusinessException(ResponseEnum::CLIENT_HTTP_UNAUTHORIZED_EXPIRED, 'token not exist');
        }

        $jwt = new JwtService();

        $parse = $jwt->decode($token);

        $admin = Admin::query()->find($parse->data->user_id);

        if (is_null($admin)) {
            throw new BusinessException(ResponseEnum::CLIENT_HTTP_UNAUTHORIZED, '用户未注册或已注销');
        }

        $request->attributes->set('admin_info', $admin);

        return $next($request);
    }
}
